/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.tutwiz.persistence;


import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import net.tutwiz.model.User;
import org.omg.PortableInterceptor.USER_EXCEPTION;

/**
 *
 * @author danielwirdehall
 */
@Stateless
public class UserPersistenceManager implements IPersistenceManager<User> {

//    @PersistenceContext(unitName = "TutWizPU")
    private EntityManager em;

    public UserPersistenceManager() {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("TutWizPU");
        em = emf.createEntityManager();
    }
    
    public UserPersistenceManager(boolean testing) {   
        em = Persistence.createEntityManagerFactory("TutwizTestPU").createEntityManager();
    }
    
    @Override
    public void save(User u) {
        em.getTransaction().begin();
        em.persist(u);
        em.getTransaction().commit();
    }

    @Override
    public void delete(User u) {
        em.getTransaction().begin();
        em.remove(u);
        em.getTransaction().commit();
    }

    @Override
    public void update(User u) {
        em.getTransaction().begin();
        em.merge(u);
        em.getTransaction().commit();
    }

    @Override
    public User get(Long id) {
        return em.find(User.class, id);
    }
	
	
	public User get(String name) {
            
                //Vi vet att native query är förbjudet, men vi kan inte använda metamodels, vi har dock kodat nedan hur det borde vara
		Query q = em.createQuery("SELECT u FROM tutorialUser u WHERE u.name='" + name + "'");
		return (User)q.getResultList().get(0);
		// DETTA FUNKAR INTE FÖR ATT VI INTE HAR METAMODELS?!?!?!?!
		/*CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
		Root<User> userRoot = cq.from(User.class);
        //cq.select(userRoot).where(cq.equals(userRoot_.name), name);
        return (User)em.createQuery(cq).getResultList().get(0);*/
	}
	
    @Override
    public List<User> getAll() {
        CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        cq.select(cq.from(User.class));
        return em.createQuery(cq).getResultList();
    }

    @Override
    public EntityManager getEntityManager() {
        return em;
    }

    @Override
    public void setEntityManager(EntityManager em) {
        this.em = em;
    }

    @Override
    public int count() {
        CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        Root<User> rt = cq.from(User.class);
        cq.select(em.getCriteriaBuilder().count(rt));
        Query q = em.createQuery(cq);
        return ((Long) q.getSingleResult()).intValue();
    }
    
}